<script setup lang="ts" name="MainMedication">
import {computed, onBeforeUnmount, onDeactivated, onMounted, reactive, ref} from 'vue'
import {HeaderData, Operation as Opr} from '@/components/dTable/dTable'
import dTablePromote from '@/components/dTable/dTable.vue'
import operation from '@/components//dTable/components/operation.vue'
import dIcon from '@/components/dIcon.vue'
import DrugStorehouse from './drugStorehouse/index.vue'
import {ColorRed, ColorTheme, IconConfig, SeleteData} from '@/api/config'
import {FormRules} from 'element-plus'
import {NotLeadingAndTrailingSpaces, transfDicArrData} from '@/util/common'
import {ElMessage} from 'element-plus/es'
import useUser from '@/store/user'
import userCommon from '@/store/common'
import {getDrugStoreByName, getMainMedication, MainMedication, rejectMainMedication, saveMainMedication} from '@/api/medicalExaminerDesk/beginPhysicalExamination/mainMedication'
import {fieldRequired} from '@/api/medicalExaminerDesk/beginPhysicalExamination'
import {showMessageBox} from '@/util/element'
const user = useUser.setup().store
const common = userCommon.setup().store

const props = defineProps({
  // 体检登记表id
  checkupRegisterId: {
    type: String,
    required: true,
    default: ''
  },
  // 禁止编辑
  disEdit: {
    type: Boolean,
    required: true,
    default: false
  },
  // 性别
  gender: {
    type: String,
    required: false,
    default: ''
  }
})

// 保存和拒检的加载
const showSaveLoading = ref<boolean>(false)

// 表格加载
const showLoading = ref(false)

//体检医生id
const dutyDoctorId = ref<string | undefined>()
// 体检医生姓名
const dutyDoctorName = ref<string | undefined>()

// 用法
const drugUseMethodOptions = ref<Array<SeleteData>>([])
// 用药频率
const frequencyOptions = ref<Array<SeleteData>>([])

// 剂量单位
const doseUnitOptions = ref<Array<SeleteData>>([])

// 时间单位
const drugTimeUnitOptions = ref<Array<SeleteData>>([])

// 服药依从性
const drugCompliableOptions = ref<Array<SeleteData>>([])

// 控制是否现在校验提示
const showErrorTips = ref<boolean>(true)

// 错提示图标
const errorIcon: IconConfig = {
  icon: 'CircleCloseFilled',
  type: 'el',
  size: 16,
  color: ColorRed
}

// 表单实例
const formRef = ref()

// 体检大类的体检医生姓名
const dutyDoctorName7 = computed(() => {
  return dutyDoctorName.value || (user.userInfor?.jobName === '医生' ? user.userInfor?.userName : '')
})

//表格头数据
const tableHeaderDatas = ref<Array<HeaderData>>([
  {prop: 'drugName', label: '药物名称', columnType: 'slot', align: 'left', 'min-width': '200'},
  {prop: 'drugUseMethod', label: '用法', columnType: 'slot', align: 'left', width: '150'},
  {prop: 'consumption', label: '用量', columnType: 'slot', align: 'left', width: '480'},
  {prop: 'administrationTime', label: '用药时间', columnType: 'slot', align: 'left', width: '320'},
  {prop: 'drugCompliable', label: '服药依从性', columnType: 'slot', align: 'left', width: '190'},
  {prop: 'operation', label: '操作', columnType: 'slot', width: '83'}
])

// 禁止编辑的时候去掉操作列
props.disEdit && (tableHeaderDatas.value = tableHeaderDatas.value.slice(0, -1))

const tableHeaderBtnIcon: IconConfig = {icon: 'common-drug-storehouse', type: 'custom', size: 16}

// 操作按钮数据
const operationDataDelete: Array<Opr> = [
  {
    code: 'delete',
    label: '删除',
    iconConfig: {icon: 'common-delete', type: 'custom', color: ColorRed, size: 20}
  }
]

// 操作按钮数据
const operationDataAdd: Array<Opr> = [
  {
    code: 'add',
    label: '添加',
    iconConfig: {icon: 'common-swap-add', type: 'custom', color: ColorTheme, size: 20}
  }
]

// 药品库维护弹窗
const showDialog = ref(false)

const rules = computed<FormRules>(() => {
  return {
    drugName: [
      {required: fieldRequired('drugName'), message: '请输入药品名称!', trigger: []},
      {
        message: '最多50个字符!',
        trigger: ['change', 'blur'],
        max: 50
      },
      {
        message: '首尾不能为空格!',
        pattern: NotLeadingAndTrailingSpaces,
        trigger: ['change', 'blur']
      }
    ],
    drugUseMethod: [{required: fieldRequired('drugUseMethod'), message: '请选择用法!', trigger: ['change']}],
    frequency: [{required: fieldRequired('frequency'), message: '请选择用药频率!', trigger: ['change']}],
    dose: [
      {required: fieldRequired('dose'), message: '请输入用药剂量!', trigger: ['change']},
      {
        message: '最多20个字符!',
        trigger: ['change', 'blur'],
        max: 20
      },
      {
        message: '首尾不能为空格!',
        pattern: NotLeadingAndTrailingSpaces,
        trigger: ['change', 'blur']
      }
    ],
    doseUnit: [{required: fieldRequired('doseUnit'), message: '请选择剂量单位!', trigger: ['change']}],
    drugUseTime: [{required: fieldRequired('drugUseTime'), message: '请输入用药时间!', trigger: ['change']}],
    drugTimeUnit: [{required: fieldRequired('drugTimeUnit'), message: '请选择用药时间单位!', trigger: ['change']}],
    drugCompliable: [{required: fieldRequired('drugCompliable'), message: '请选择服药依从性!', trigger: ['change']}]
  }
})

// 空数据表格
const emptyTableData: MainMedication = {}

// 主要用药情况列表
const formData = reactive<{mainMedicationTable: Array<MainMedication>}>({
  mainMedicationTable: [
    {...emptyTableData, ...{operation: operationDataAdd}},
    {...emptyTableData, ...{operation: operationDataAdd}}
  ]
})

// 体检状态
const checkupStatus7 = computed(() => {
  return formData.mainMedicationTable[0]?.checkupStatus
})

/**
 * @description: 添加展示按钮
 * @param {*} dataList
 * @return {*}
 */
const showButton = (dataList: Array<MainMedication>) => {
  formRef.value.clearValidate() // 清空校验
  const returnList: Array<MainMedication> = []
  dataList.map((item, index) => {
    returnList.push({...item, operation: index === dataList.length - 1 ? [...operationDataAdd, ...operationDataDelete] : operationDataDelete})
  })
  return returnList
}

/**
 * @description: 删除主要用药情况
 * @param {*} index
 * @return {*}
 */
const onRemoveMainMedication = (index: number) => {
  formData.mainMedicationTable.splice(index, 1)
  formData.mainMedicationTable = showButton(formData.mainMedicationTable)
  if (formData.mainMedicationTable.length === 0) {
    formData.mainMedicationTable = [{...emptyTableData, ...{operation: operationDataAdd}}]
  }
}

/**
 * @description: 添加主要用药情况
 * @return {*}
 */
const onAddMainMedication = () => {
  formData.mainMedicationTable.push(emptyTableData)
  formData.mainMedicationTable = showButton(formData.mainMedicationTable)
}

/**
 * @description: 主要用药情况列表操作栏点击
 * @param {*} code
 * @param {*} row
 * @return {*}
 */
const onMainMedicationTableOper = (code: string, row: MainMedication) => {
  if (code === 'delete') {
    onRemoveMainMedication(formData.mainMedicationTable.indexOf(row))
  } else if (code === 'add') {
    onAddMainMedication()
  }
}

/**
 * @description: 获取体检信息
 * @return {*}
 */
const getInitData = () => {
  showLoading.value = true
  getMainMedication(props.checkupRegisterId)
    .then((res) => {
      const {data} = res.data || []
      data?.length &&
        data?.forEach((item) => {
          // 类型转换，转数字
          item.drugUseTime = item.drugUseTime ? Number(item.drugUseTime) : undefined
          // 获取当前行的体检医生
          item.dutyDoctorId && (dutyDoctorId.value = item.dutyDoctorId)
          item.dutyDoctorName && (dutyDoctorName.value = item.dutyDoctorName)
          item.dose = item.dose || undefined
          item.drugUseMethod = item.drugUseMethod || undefined
          item.frequency = item.frequency || undefined
          item.doseUnit = item.doseUnit || undefined
          item.drugTimeUnit = item.drugTimeUnit || undefined
          item.drugCompliable = item.drugCompliable || undefined
        })
      data?.length && (formData.mainMedicationTable = data)
      if (formData.mainMedicationTable?.length === 0) {
        formData.mainMedicationTable = [{...emptyTableData, ...{operation: operationDataAdd}}]
      }
      formData.mainMedicationTable = showButton(formData.mainMedicationTable)
    })
    .finally(() => {
      showLoading.value = false
      showSaveLoading.value = false
      formRef.value?.clearValidate()
    })
}

/**
 * @description: 保存
 * @return {*}
 */
const onSave7 = () => {
  showErrorTips.value = true
  formRef.value &&
    formRef.value.validate((valid: boolean, fields) => {
      if (valid) {
        showSaveLoading.value = true
        const params = formData.mainMedicationTable.map((item) => {
          return {
            id: item.id,
            checkupStatus: 2, //2已检
            checkupRegisterId: props.checkupRegisterId,
            dutyDoctorId: dutyDoctorId.value || user.userInfor?.id,
            dutyDoctorName: dutyDoctorId.value !== user.userInfor?.id ? dutyDoctorName.value || user.userInfor?.userName : user.userInfor?.userName,
            drugName: item.drugName, // 药品名称
            drugUseMethod: item.drugUseMethod, // 用法 - 字典
            frequency: item.frequency, // 用药频率 - 字典
            dose: item.dose, // 用药剂量
            doseUnit: item.doseUnit, // 用药剂量单位 - 字典
            drugTimeUnit: item.drugTimeUnit, //用药时间单位 - 字典
            drugUseTime: item.drugUseTime, // 用药时间
            drugCompliable: item.drugCompliable // 服药依从性 - 字典
          }
        })
        saveMainMedication(params)
          .then(() => {
            getInitData()
            ElMessage.success('保存成功!')
          })
          .catch((err) => {
            console.warn(err)
            showSaveLoading.value = false
          })
      } else {
        console.warn(fields)
      }
    })
}

/**
 * @description: 拒检
 * @return {*}
 */
const onRejectInspection7 = () => {
  showMessageBox('是否对该体检大类进行拒检操作？', {title: '拒检确认', mesageType: 'base'})
    .then(() => {
      showSaveLoading.value = true
      const params = formData.mainMedicationTable.map((item) => {
        return {
          id: item.id,
          checkupStatus: 1, // 1拒检
          checkupRegisterId: props.checkupRegisterId,
          dutyDoctorId: dutyDoctorId.value || user.userInfor?.id,
          dutyDoctorName: dutyDoctorId.value !== user.userInfor?.id ? dutyDoctorName.value || user.userInfor?.userName : user.userInfor?.userName,
          drugName: null, // 药品名称
          drugUseMethod: null, // 用法 - 字典
          frequency: null, // 用药频率 - 字典
          dose: null, // 用药剂量
          doseUnit: null, // 用药剂量单位 - 字典
          drugTimeUnit: null, //用药时间单位 - 字典
          drugUseTime: null, // 用药时间
          drugCompliable: null // 服药依从性 - 字典
        }
      })
      rejectMainMedication(params)
        .then(() => {
          ElMessage.success('拒检成功!')
          getInitData()
        })
        .catch((error) => {
          showSaveLoading.value = false
          console.warn(error)
        })
    })
    .catch((error) => {
      console.warn(error)
    })
}

/**
 * @description: 搜索药物名称
 * @param {*} drugName 药物名称
 * @param {*} cb
 * @return {*}
 */
const searchDrugName = (drugName: string, cb) => {
  // 长度校验，和首尾空格校验不通过不请求数据
  if (drugName.length > 50 || !NotLeadingAndTrailingSpaces.test(drugName)) {
    cb([])
    return
  }
  getDrugStoreByName({drugName}).then((res) => {
    const {data} = res.data || []
    cb(data)
  })
}

/**
 * @description: 选择药物名称
 * @param {*} item 下拉值
 * @param {*} index // 表格的行下标
 * @return {*}
 */
const handleSelect = (item, index: number) => {
  formData.mainMedicationTable[index].drugName = item.drugName //药物名称
  formData.mainMedicationTable[index].drugUseMethod = item.drugUseMethod // 用法 - 字典
  formData.mainMedicationTable[index].frequency = item.frequency // 用药频率 - 字典
  formData.mainMedicationTable[index].dose = item.dose // 用药剂量
  formData.mainMedicationTable[index].doseUnit = item.doseUnit // 用药剂量单位 - 字典
  formData.mainMedicationTable[index].drugUseTime = Number(item.drugUseTime) || undefined // 用药时间
  formData.mainMedicationTable[index].drugTimeUnit = item.drugTimeUnit //用药时间单位 - 字典
  formData.mainMedicationTable[index].drugCompliable = item.drugCompliable // 服药依从性 - 字典
}

/**
 * @description: 获取下拉字典
 * @return {*}
 */
const getDict = () => {
  drugUseMethodOptions.value.length = 0 // 用法
  frequencyOptions.value.length = 0 // 用药频率
  doseUnitOptions.value.length = 0 // 剂量单位
  drugTimeUnitOptions.value.length = 0 // 时间单位
  drugCompliableOptions.value.length = 0 // 服药依从性
  // 用法字典
  common.getDicData('drug_use_method').then((res) => {
    const arr: Array<SeleteData> = transfDicArrData(res)
    arr.forEach((item) => {
      drugUseMethodOptions.value.push(item)
    })
  })
  // 用药频率字典
  common.getDicData('frequency').then((res) => {
    const arr: Array<SeleteData> = transfDicArrData(res)
    arr.forEach((item) => {
      frequencyOptions.value.push(item)
    })
  })
  // 用药剂量单位字典
  common.getDicData('dose_unit').then((res) => {
    const arr: Array<SeleteData> = transfDicArrData(res)
    arr.forEach((item) => {
      doseUnitOptions.value.push(item)
    })
  })
  // 用药时间单位字典
  common.getDicData('drug_time_unit').then((res) => {
    const arr: Array<SeleteData> = transfDicArrData(res)
    arr.forEach((item) => {
      drugTimeUnitOptions.value.push(item)
    })
  })
  // 服药依从性字典
  common.getDicData('drug_compliable').then((res) => {
    const arr: Array<SeleteData> = transfDicArrData(res)
    arr.forEach((item) => {
      drugCompliableOptions.value.push(item)
    })
  })
}

onMounted(() => {
  getInitData()
  getDict()
})

onBeforeUnmount(() => {
  showErrorTips.value = false
})

onDeactivated(() => {
  showErrorTips.value = false
})
</script>

<template>
  <div class="d-check-up-desk-content">
    <el-button v-blur type="primary" class="table-header-btn" @click="showDialog = true">
      <d-icon class="el-icon el-icon--left" :icon-config="tableHeaderBtnIcon" />
      药品库维护
    </el-button>
    <el-form ref="formRef" :rules="rules" :model="formData" :disabled="disEdit">
      <d-table-promote class="d-common-flex-full main-medication-table" :table-data="formData.mainMedicationTable" :table-header-data="tableHeaderDatas" :show-loading="showLoading">
        <template #drugName="scope">
          <el-form-item :prop="`mainMedicationTable.${scope.index}.drugName`" :rules="rules.drugName" :inline-message="true" class="d-common-width-full">
            <el-autocomplete
              v-model="scope.row.drugName"
              placeholder="请输入药物名称"
              :fetch-suggestions="searchDrugName"
              :debounce="600"
              :highlight-first-item="true"
              :trigger-on-focus="false"
              :fit-input-width="true"
              :clearable="true"
              @select="
                (item) => {
                  handleSelect(item, scope.index)
                }
              "
            >
              <template #default="{item}">
                <div class="value">
                  药品名称：{{ item.drugName }}(药品代码:{{ item.drugCode }} )
                </div>
              </template>
            </el-autocomplete>
            <template #error="{error}">
              <div>
                <el-popover
                  :visible="showErrorTips"
                  :width="200"
                  :hide-after="0"
                  :persistent="false"
                  transition="none"
                  placement="right"
                  popper-class="error-tip"
                >
                  <d-icon :icon-config="errorIcon" />
                  {{ error }}
                  <template #reference>
                    <span />
                  </template>
                </el-popover>
              </div>
            </template>
          </el-form-item>
        </template>
        <template #drugUseMethod="scope">
          <el-form-item :prop="`mainMedicationTable.${scope.index}.drugUseMethod`" :rules="rules.drugUseMethod" :inline-message="true">
            <el-select v-model="scope.row.drugUseMethod" placeholder="请选择用法" clearable>
              <el-option v-for="item in drugUseMethodOptions" :key="item.value + ''" :label="item.label" :value="item.value" />
            </el-select>
            <template #error="{error}">
              <div>
                <el-popover
                  :visible="showErrorTips"
                  :width="200"
                  :hide-after="0"
                  :persistent="false"
                  transition="none"
                  placement="right"
                  popper-class="error-tip"
                >
                  <d-icon :icon-config="errorIcon" />
                  {{ error }}
                  <template #reference>
                    <span />
                  </template>
                </el-popover>
              </div>
            </template>
          </el-form-item>
        </template>
        <template #consumption="scope">
          <el-form-item :prop="`mainMedicationTable.${scope.index}.frequency`" :rules="rules.frequency" :inline-message="true">
            <el-select v-model="scope.row.frequency" placeholder="请选择用药频率" clearable class="width-1evel-2">
              <el-option v-for="item in frequencyOptions" :key="item.value + ''" :label="item.label" :value="item.value" />
            </el-select>
            <template #error="{error}">
              <div>
                <el-popover
                  :visible="showErrorTips"
                  :width="200"
                  :hide-after="0"
                  :persistent="false"
                  transition="none"
                  placement="right"
                  popper-class="error-tip"
                >
                  <d-icon :icon-config="errorIcon" />
                  {{ error }}
                  <template #reference>
                    <span />
                  </template>
                </el-popover>
              </div>
            </template>
          </el-form-item>
          <el-form-item :prop="`mainMedicationTable.${scope.index}.dose`" :rules="rules.dose" :inline-message="true">
            <el-input v-model="scope.row.dose" placeholder="请输入用药剂量" clearable class="width-1evel-2 margin-level-2" />
            <template #error="{error}">
              <div>
                <el-popover
                  :visible="showErrorTips"
                  :width="200"
                  :hide-after="0"
                  :persistent="false"
                  transition="none"
                  placement="right"
                  popper-class="error-tip"
                >
                  <d-icon :icon-config="errorIcon" />
                  {{ error }}
                  <template #reference>
                    <span />
                  </template>
                </el-popover>
              </div>
            </template>
          </el-form-item>
          <el-form-item :prop="`mainMedicationTable.${scope.index}.doseUnit`" :rules="rules.doseUnit" :inline-message="true">
            <el-select v-model="scope.row.doseUnit" placeholder="请选择剂量单位" clearable class="width-1evel-2">
              <el-option v-for="item in doseUnitOptions" :key="item.value + ''" :label="item.label" :value="item.value" />
            </el-select>
            <template #error="{error}">
              <div>
                <el-popover
                  :visible="showErrorTips"
                  :width="200"
                  :hide-after="0"
                  :persistent="false"
                  transition="none"
                  placement="right"
                  popper-class="error-tip"
                >
                  <d-icon :icon-config="errorIcon" />
                  {{ error }}
                  <template #reference>
                    <span />
                  </template>
                </el-popover>
              </div>
            </template>
          </el-form-item>
        </template>
        <template #administrationTime="scope">
          <el-form-item :prop="`mainMedicationTable.${scope.index}.drugUseTime`" :rules="rules.drugUseTime" :inline-message="true">
            <el-input-number v-model="scope.row.drugUseTime" placeholder="请输入用药时间" :controls="false" :max="9999" clearable class="width-1evel-2 margin-level-1" />
            <template #error="{error}">
              <div>
                <el-popover
                  :visible="showErrorTips"
                  :width="200"
                  :hide-after="0"
                  :persistent="false"
                  transition="none"
                  placement="right"
                  popper-class="error-tip"
                >
                  <d-icon :icon-config="errorIcon" />
                  {{ error }}
                  <template #reference>
                    <span />
                  </template>
                </el-popover>
              </div>
            </template>
          </el-form-item>
          <el-form-item :prop="`mainMedicationTable.${scope.index}.drugTimeUnit`" :rules="rules.drugTimeUnit" :inline-message="true">
            <el-select v-model="scope.row.drugTimeUnit" placeholder="请选择时间单位" clearable class="width-1evel-2">
              <el-option v-for="item in drugTimeUnitOptions" :key="item.value + ''" :label="item.label" :value="item.value" />
            </el-select>
            <template #error="{error}">
              <div>
                <el-popover
                  :visible="showErrorTips"
                  :width="200"
                  :hide-after="0"
                  :persistent="false"
                  transition="none"
                  placement="right"
                  popper-class="error-tip"
                >
                  <d-icon :icon-config="errorIcon" />
                  {{ error }}
                  <template #reference>
                    <span />
                  </template>
                </el-popover>
              </div>
            </template>
          </el-form-item>
        </template>
        <template #drugCompliable="scope">
          <el-form-item :prop="`mainMedicationTable.${scope.index}.drugCompliable`" :rules="rules.drugCompliable" :inline-message="true">
            <el-select v-model="scope.row.drugCompliable" placeholder="请选择服药依从性" clearable>
              <el-option v-for="item in drugCompliableOptions" :key="item.value + ''" :label="item.label" :value="item.value" />
            </el-select>
            <template #error="{error}">
              <div>
                <el-popover
                  :visible="showErrorTips"
                  :width="200"
                  :hide-after="0"
                  :persistent="false"
                  transition="none"
                  placement="top"
                  popper-class="error-tip"
                >
                  <d-icon :icon-config="errorIcon" />
                  {{ error }}
                  <template #reference>
                    <span />
                  </template>
                </el-popover>
              </div>
            </template>
          </el-form-item>
        </template>
        <template #operation="scope">
          <operation :row="scope.row" :col="scope.item" @opertion-click="onMainMedicationTableOper" />
        </template>
      </d-table-promote>
    </el-form>
  </div>
  <div class="d-check-up-desk-footer d-common-flex-center d-common-width-full">
    <span class="doctor">体检医生：</span>
    <el-input v-model="dutyDoctorName7" disabled />
    <el-button type="primary" :loading="showSaveLoading" :disabled="disEdit" @click="onSave7()">
      保存
    </el-button>
    <el-button type="danger" :loading="showSaveLoading" :disabled="(checkupStatus7 && checkupStatus7 === 1) || disEdit" plain @click="onRejectInspection7()">
      拒检
    </el-button>
  </div>
  <drug-storehouse v-if="showDialog" :show-dialog="showDialog" @close="showDialog = false" />
</template>

<style scoped lang="less">
.table-header-btn {
  margin-bottom: 20px;
}
.main-medication-table {
  min-height: 65vh;
  .el-form-item {
    display: inline-flex;
    margin: 0;
    :deep(.el-form-item__error) {
      top: 18px;
      left: 10px;
    }
  }
}
.width-1evel-1 {
  width: 100px;
}
.width-1evel-2 {
  width: 141px;
}
.width-1evel-3 {
  width: 152px;
}
.margin-level-1 {
  margin-right: 4px;
}
.margin-level-2 {
  margin-left: 4px;
  margin-right: 4px;
}
:deep(.el-autocomplete) {
  width: 100%;
}
</style>
